import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'SizeTween Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: SizeTweenDemo(),
    );
  }
}

class SizeTweenDemo extends StatefulWidget {
  @override
  _SizeTweenDemoState createState() => _SizeTweenDemoState();
}

class _SizeTweenDemoState extends State<SizeTweenDemo> with SingleTickerProviderStateMixin {
  // 创建一个 AnimationController
  late AnimationController _controller;

  // 定义一个 SizeTween 来控制容器大小的动画
  late Animation<Size?> _sizeAnimation;

  // 标记容器的状态，控制是否从小到大或大到小
  bool _isLarge = false;

  @override
  void initState() {
    super.initState();

    // 创建 AnimationController，设置动画时长为 2 秒
    _controller = AnimationController(
      duration: const Duration(seconds: 2),
      vsync: this,
    );


    // 使用 SizeTween 来定义动画范围（从 100x100 到 300x300）
    _sizeAnimation = SizeTween(
      begin: Size(100.0, 100.0), // 初始大小
      end: Size(200.0, 200.0), // 结束大小
    ).animate(_controller
    );

    // 监听动画完成的状态
    _controller.addStatusListener((status) {
      if (status == AnimationStatus.completed) {
        // 动画完成时，切换容器状态
        setState(() {
          _isLarge = true;
        });
      } else if (status == AnimationStatus.dismissed) {
        // 动画回退完成时，切换容器状态
        setState(() {
          _isLarge = false;
        });
      }
    });
  }

  @override
  void dispose() {
    // 释放 AnimationController 资源
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('SizeTween Demo'),
      ),
      body: Center(
        child: AnimatedBuilder(
          animation: _sizeAnimation,
          builder: (context, child) {
            return Container(
              width: _sizeAnimation.value?.width,
              height: _sizeAnimation.value?.height,
              color: Colors.blue,
              child: Center(
                child: Text(
                  'Animating!',
                  style: TextStyle(color: Colors.white, fontSize: 20),
                ),
              ),
            );
          },
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          // 控制动画的启动和反向
          if (!_controller.isAnimating) {
            if (_isLarge) {
              _controller.reverse(); // 从大到小
            } else {
              _controller.forward(); // 从小到大
            }
          }
        },
        child: Icon(Icons.play_arrow),
      ),
    );
  }
}
